package com.moniteach.server.servlet;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

import com.moniteach.server.db.bo.UserInfo;
import com.moniteach.server.db.connector.PMF;
import com.moniteach.utils.Resource;

public class UserInfoServlet extends CommonServlet {
	private String action = "";
	private String id = "";
	private String email = "";
	private String pass = "";
	private String fName = "";
	private String lName = "";
	private String sName = "";
	private String phone = "";
	private String role = "";
	private String pincode = "";
	private String active = "";

	@Override
	protected void prepare(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("UTF-8");

		action = req.getParameter(Resource.Const.action);
		if ("".equals(action) || action == null) {
			resp.getWriter().print(Resource.Const.no + "ACTION");
			return;
		}

		id = req.getParameter(Resource.Const.id);
		email = req.getParameter(Resource.Const.email);
		pass = req.getParameter(Resource.Const.pass);
		fName = req.getParameter(Resource.Const.fName);
		lName = req.getParameter(Resource.Const.lName);
		sName = req.getParameter(Resource.Const.sName);
		phone = req.getParameter(Resource.Const.phone);
		role = req.getParameter(Resource.Const.role);
		pincode = req.getParameter(Resource.Const.pincode);
		active = req.getParameter(Resource.Const.active);

		String response = "";
		if (Resource.Action.CREATE.equals(action)) {
			response = create();
		} else if (Resource.Action.GET.equals(action)) {
			response = getById();
		} else if (Resource.Action.MODIFY.equals(action)) {
			response = modify();
		} else if (Resource.Action.AUTH.equals(action)) {
			response = auth();
		} else if (Resource.Action.GET_ALL.equals(action)) {
			response = getAll();
		}
		resp.getWriter().print(response);

	}

	@Override
	protected String create() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(UserInfo.class);
		try {
			query.setFilter(String.format("email == '%1$s'", email));
			List<UserInfo> results = (List<UserInfo>) query.execute();
			if (results.isEmpty()) {
				Boolean activeBoolean = Boolean.valueOf(active);
				UserInfo oneUser = new UserInfo(email, pass, fName, lName,
						sName, phone, role, pincode, activeBoolean);
				pm.makePersistent(oneUser);
				return String.valueOf(oneUser.getId());
			} else {
				return Resource.Const.no;
			}
		} catch (Exception e) {
			return Resource.Const.no;
		} finally {
			pm.close();
		}
	}

	@Override
	protected String getById() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Long idLong = Long.valueOf(id);
			UserInfo entityUser = pm.getObjectById(UserInfo.class, idLong);
			return entityUser.toJSONObject().toString();
		} catch (Exception e) {
			return Resource.Const.no;
		} finally {
			pm.close();
		}

	}

	@Override
	protected String modify() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Long idLong = Long.valueOf(id);
			UserInfo entityUser = pm.getObjectById(UserInfo.class, idLong);

			Boolean activeBoolean = Boolean.valueOf(active);

			if (email != null) {
				entityUser.setEmail(email);
			}
			if (pass != null) {
				entityUser.setPass(pass);
			}
			if (fName != null) {
				entityUser.setfName(fName);
			}
			if (lName != null) {
				entityUser.setlName(lName);
			}
			if (sName != null) {
				entityUser.setsName(sName);
			}
			if (phone != null) {
				entityUser.setPhone(phone);
			}
			if (role != null) {
				entityUser.setRole(role);
			}
			if (pincode != null) {
				entityUser.setPincode(pincode);
			}
			entityUser.setActive(activeBoolean);

			pm.makePersistent(entityUser);
			return Resource.Const.ok;
		} catch (Exception e) {
			return Resource.Const.no;
		} finally {
			pm.close();
		}
	}

	private String auth() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(UserInfo.class);
		try {
			// if (pass == null) {
			// query.setFilter(String.format(
			// "email == '%1$s' && password == null", email));
			// } else {
			query.setFilter(String.format(
					"email == '%1$s' && pass == '%2$s'", email, pass));
			// }
			List<UserInfo> results = (List<UserInfo>) query.execute();
			if (results.size() == 1) {
				return results.get(0).toJSONObject().toString();
			} else
				return Resource.Const.no;
		} catch (Exception e) {
			return Resource.Const.no + " " + e;
		} finally {
			pm.close();
		}
	}

	@Override
	protected String getAll() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(UserInfo.class);
		try {
			query.setFilter("active == true");
			List<UserInfo> results = (List<UserInfo>) query.execute();
			JSONArray array = new JSONArray();
			if (results.size() > 0) {
				for (UserInfo userInfo : results) {
					array.put(userInfo.toJSONObject());
				}
				return array.toString();
			} else
				return Resource.Const.no;

		} catch (Exception e) {
			return Resource.Const.no + e;
		} finally {
			pm.close();
		}
	}

	@Override
	protected String get() {
		return null;
	}

}
